package com.mxpio.erp.workshop.controller;

import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.common.workshop.entity.OoPickingNotice;
import com.mxpio.erp.common.workshop.service.OoPickingNoticeService;
import com.mxpio.erp.workshop.policy.impl.DefaultOoInNoticePolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Tag(name = "OoPickingNoticeController", description = "委外领/退/补通知单接口")
@RestController
@RequestMapping("/erp/workshop/op/")
public class OoPickingNoticeController {

    @Autowired
    private OoPickingNoticeService service;
    
    @Autowired
    private NoticeService noticeService;

   /* @Autowired
    private ItemService itemService;

    @Autowired
    private OoPickingNoticeLineService ooPickingNoticeLineService;*/
    @GetMapping("list")
    @Operation(summary = "委外领/退/补通知单列表", description = "获取委外领/退/补通知单列表（无分页）", method = "GET")
    public Result<List<OoPickingNotice>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<OoPickingNotice> ooPickingNotice = service.list(OoPickingNotice.class, criteria);
        return Result.OK(ooPickingNotice);
    }

    @GetMapping("page")
    @Operation(summary = "委外领/退/补通知单列表", description = "获取委外领/退/补通知单列表（分页）", method = "GET")
    public Result<Page<OoPickingNotice>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<OoPickingNotice> ooPickingNotice = service.listPage(OoPickingNotice.class, page, criteria);
        return Result.OK(ooPickingNotice);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取委外领/退/补通知单", description = "根据noticeNo获取委外领/退/补通知单", method = "GET")
    public Result<OoPickingNotice> getById(@Parameter(description="业务单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        OoPickingNotice ooPickingNotice = service.getById(OoPickingNotice.class, noticeNo);
        return Result.OK(ooPickingNotice);
    }


    @RequestMapping("excute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    @Transactional
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo, 
    		@RequestBody OrderExcuteVo orderExcuteVo) {
    	OoPickingNotice notice = service.getById(OoPickingNotice.class, noticeNo);
        if (org.apache.commons.lang3.StringUtils.equals(notice.getNoticeStatus(),NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
            return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认");
        }
    	NoticeContext context = noticeService.execute(notice, new DefaultOoInNoticePolicy(orderExcuteVo.getLines()));
    	if(CollectionUtils.isEmpty(context.getErrors())) {
    		return Result.OK();
    	}else {
    		return Result.error(context.getErrors().get(0));
    	}
    }


    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除委外领/退/补通知单", description = "删除委外领/退/补通知单", method = "DELETE")
    @Transactional
    public Result<OoPickingNotice> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            service.delete(OoPickingNotice.class, key);
        }
        return Result.OK();
    }
    
    @PutMapping("reject/{noticeNo}")
    @Operation(summary = "拒绝通知单", description = "拒绝通知单", method = "PUT")
    @Transactional
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
    	OoPickingNotice ooPickingNotice = service.getById(OoPickingNotice.class,noticeNo);
    	return noticeService.updateNoticeStatus(ooPickingNotice, NoticeStatusEnums.NoticeStatus.REJECT);
    }

    /*@PutMapping("commit/{noticeNo}")
    @Operation(summary = "提交通知单", description = "提交通知单", method = "PUT")
    @Transactional
    public Result<? extends Notice> commit(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        OoPickingNotice ooPickingNotice = service.getById(OoPickingNotice.class,noticeNo);
        if (!StringUtils.equals(ooPickingNotice.getNoticeStatus(),NoticeStatusEnums.NoticeStatus.DRAFT.getStatusCode())){
            return Result.error("仅草稿状态的单据可以执行提交操作");
        }
        return noticeService.updateNoticeStatus(ooPickingNotice, NoticeStatusEnums.NoticeStatus.CREATE);
    }*/

   /* @GetMapping("export")
    @Operation(summary = "委外领/退/补通知单列表导出", description = "获取委外领/退/补通知单列表导出", method = "GET")
    public Result<List<MoPickingNoticeExportVO>> export(@Parameter(description="查询参数") Criteria criteria){
        List<OoPickingNotice> ooPickingNotice = service.list(OoPickingNotice.class, criteria);
        List<MoPickingNoticeExportVO> exportVOList = new ArrayList<>();
        if (ooPickingNotice.size()>0){
            for (OoPickingNotice notice:ooPickingNotice){
                Criteria c = Criteria.create().addCriterion("noticeNo", Operator.EQ, notice.getNoticeNo());
                c.addOrder(new Order("lineNo",false));//按lineno升序
                List<OoPickingNoticeLine> ooPickingNoticeLines = ooPickingNoticeLineService.list(OoPickingNoticeLine.class, c);
                if (ooPickingNoticeLines.size()>0){
                    for (OoPickingNoticeLine line:ooPickingNoticeLines){
                        MoPickingNoticeExportVO exportVO = new MoPickingNoticeExportVO();
                        BeanReflectionUtils.copyProperties(exportVO, notice);
                        BeanReflectionUtils.copyProperties(exportVO, line);
                        exportVOList.add(exportVO);
                    }
                }
            }
        }
        return Result.OK(exportVOList);
    }*/

    @GetMapping("listbynos/{noticeNos}")
    @Operation(summary = "根据noticeNos获取对应通知单及明细", description = "根据noticeNos获取通知单及明细", method = "GET")
    public Result<List<OoPickingNotice>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
        return service.listByIds(noticeNos);
    }
}
